package org.itzheng.base;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;

import org.itzheng.itplayer.MainActivity;
import org.vetc.mgr.base.BaseKotlinFragment;

/**
 * Title:<br>
 * Description: <br>
 *
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2020-7-29.
 */
public class BaseFragment extends BaseKotlinFragment {
    protected String TAG = getClass().getSimpleName();
    /**
     * 进栈id，貌似没啥用处
     */
    public Integer stackId = null;
    protected View rootView;
    int firstOrientation;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //第一次创建会调用
        firstOrientation = getActivity().getRequestedOrientation();
        Log.w(TAG, "onCreate: firstOrientation " + firstOrientation);
        //默认都启用event
//        initEventBus();
    }

//    private EventBusViewModel eventBus;
//
//    protected void postEvent(EventBusViewModel.EventMessage msg) {
//        initEventBus();
//        eventBus.post(msg);
//    }
//
//    protected void initEventBus() {
//        if (eventBus == null) {
//            eventBus = ViewModelUtils.getViewModel(getActivity(), EventBusViewModel.class);
//            eventBus.obj.observe(this, new Observer<EventBusViewModel.EventMessage>() {
//                @Override
//                public void onChanged(EventBusViewModel.EventMessage eventMessage) {
//                    onReceiveEvent(eventMessage);
//                }
//            });
//        }
//    }

//    /**
//     * 收到消息监听，去除烦人的回调
//     *
//     * @param event
//     */
//    public void onReceiveEvent(EventBusViewModel.EventMessage event) {
//
//    }

    /**
     * 设置横屏
     */
    protected void setOrientationLandscape() {
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制横屏
    }

    /**
     * 设置竖屏
     */
    protected void setOrientationPortrait() {
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制竖屏
    }

    /**
     * 还原之前的屏幕方向
     */
    protected void restoreOrientation() {
        getActivity().setRequestedOrientation(firstOrientation);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //fragment销毁会调用
    }

    /**
     * 导入布局
     *
     * @param resId
     * @return
     */
    protected View inflate(@LayoutRes int resId) {
        if (rootView == null) {
            rootView = LayoutInflater.from(getActivity()).inflate(resId, null);
            //设置可点击就不会点击穿透
            rootView.setClickable(true);
            onViewInflate(rootView);
        } else if (rootView.getParent() != null) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
        return rootView;
    }

    /**
     * view填充到界面时调用,一般来说，只执行一次
     *
     * @param rootView
     */
    public void onViewInflate(View rootView) {

    }

    long lastStartTime = 0;

    /**
     * 跳转到 Fragment
     *
     * @param fragment
     */
    public synchronized void startFragment(BaseFragment fragment) {
        //有个问题，如果startFragment，然后马上finish其他一个，此时，start的还未进入栈中，
        // finish 判断被finish的那个为栈顶，直接onback,实际上，移除的是start的
        if (System.currentTimeMillis() - lastStartTime < 300) {
            //避免重复点击
            lastStartTime = System.currentTimeMillis();
            return;
        }
        lastStartTime = System.currentTimeMillis();
        forceStartFragment(fragment);
    }

    /**
     * 强制跳转。就是不管时间间隔
     *
     * @param fragment
     */
    public synchronized void forceStartFragment(BaseFragment fragment) {
        MainActivity activity = getMainActivity();
        activity.startFragment(fragment);
    }


    /**
     * 获取 MainActivity，如果有需要估计也就是设置状态栏颜色吧
     *
     * @return
     */
    protected MainActivity getMainActivity() {
        return (MainActivity) getActivity();
    }

    public final void hideSoftInput() {
        getMainActivity().hideSoftInput();
    }

    /**
     * 是否拦截
     *
     * @return
     */
    public boolean onBackPressed() {
        return super.onBackPressed();
    }

    private boolean mIsStackTop = false;

    /**
     * 设置最新栈顶状态
     *
     * @param isStackTop
     */
    public void setStackTopStatus(boolean isStackTop) {
        if (mIsStackTop != isStackTop) {
            mIsStackTop = isStackTop;
            onStackTopChangeListener(isStackTop);
        }
    }

    /**
     * 自定义的生命周期，功能类似 onPause 和 onResume, 在新弹出fragment时会调用,isStackTop = false,当到达栈顶时也会调用 isStackTop=true
     */
    protected void onStackTopChangeListener(boolean isStackTop) {

    }

    private boolean isLoading = false;

    @Override
    public boolean isLoading() {
        return isLoading;
    }

    @Override
    public void showLoading() {
        super.showLoading();
        isLoading = true;
    }

    @Override
    public void dismissLoading() {
        super.dismissLoading();
        isLoading = false;
    }

    public void finish() {
        if (isLoading()) {
            //在移除fragment的时候，有判断是否能onback,如果isshowloading则不能onback
            dismissLoading();
        }
        getMainActivity().hideSoftInput();
        getMainActivity().removeFragment(this);
        //界面关闭，发送关闭界面的广播，避免创建界面时，因为observe造成的数据重复，这个在发送一条数据后，补会好点
//        postEvent(new EventBusViewModel.EventMessage(EventBusViewModel.EventCode.EVENT_FRAGMENT_FINISH));
    }

    /**
     * 如果设置 fitsSystemWindows 就会默认向上 多出状态栏的一块高度，需要消除
     *
     * @param view
     */
    protected void fixFitsSystemWindows(View view) {
        if (view.getFitsSystemWindows()) {
            if (view.getLayoutParams() instanceof FrameLayout.LayoutParams) {
                FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) view.getLayoutParams();
                lp.setMargins(lp.leftMargin, -getStatusBarHeight(getContext()), lp.rightMargin, lp.bottomMargin);
            }
        } else if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                fixFitsSystemWindows(innerView);
            }
        }
    }

    private int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}
